/*Java script encoding types*/
var encodeTypes = ["input", "textarea"]; 

var myExtension = {
    oldURL: null,
 
    init: function() {
		//alert("calling init2");
        gBrowser.addProgressListener(this);
    },
 
    uninit: function() {
		//alert("it is unloading..");
        gBrowser.removeProgressListener(this);
    },
    
    submitHandler : function(e) {
    	var obj = e.target;
        encodeScript(obj);
    },
 
    processNewURL: function(aURI) {
	//alert(aURI.spec);
	alert(encodeURI(aURI.spec));
	alert(isURLValnerable(aURI.spec));
	//alert(encodeURIComponent(aURI.spec));
	//gBrowser.addTab(encodeURIComponent(aURI.spec));
        //if (aURI.spec == this.oldURL) return;
		//alert(aURI.spec);
		//this.oldURL = aURI.spec;		
		if(isURLValnerable(aURI.spec)){
			getWebNavigation().loadURI(tamperValURL(aURI.spec), (nsIWebNavigation.LOAD_FLAGS_IS_LINK), null, null, null);
		}
    },
 
    // nsIWebProgressListener
    QueryInterface: XPCOMUtils.generateQI(["nsIWebProgressListener",
                                           "nsISupportsWeakReference"]),
 
    onLocationChange: function(aProgress, aRequest, aURI) {
        this.processNewURL(aURI);
    },
 
    onStateChange: function() {},
    onProgressChange: function() {},
    onStatusChange: function() {},
    onSecurityChange: function() {}
};
 
window.addEventListener("load", function() { myExtension.init() }, false);
window.addEventListener("unload", function() { myExtension.uninit() }, false);
window.addEventListener("submit", myExtension.submitHandler, false);

function encodeScript(form) {
	alert("test encode script");	
	for(var j = 0; j < encodeTypes.length; j++){
		var encodeType = encodeTypes[j];
		var cells = form.getElementsByTagName(encodeType);
		for (var i = 0; i < cells.length; i++) {		    
		    var encodedValue = cells[i].value;
		    cells[i].value = javaScriptEscape(encodedValue);	   
		}
	}	
}


function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}


function javaScriptEscape(str) {
    return String(str)
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

function isURLValnerable(url) {
	var isURLVal = false;
	if(encodeURI(url).indexOf("%253Cscript%253E") != -1){
		isURLVal = true;
	}
	
    return isURLVal;
}

function tamperValURL(url) {
	alert(url);
    return String(url)
            .replace('%3C', '\\<')
            .replace('%3E', '\\>')
            .replace('(', '\\(')
            .replace(')', '\\)');
}